# -*- coding: utf8 -*-
import sqlite3
from kivy.properties import ObjectProperty, DictProperty, StringProperty

from kivy.uix.screenmanager import Screen
import os
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.clock import Clock

from kivy.logger import Logger

from Business.ExamConfig import ExamConfig

from EasyLangLearnButton import EasyLangLearnButtonLang
from EasyLangLearnAccordion import EasyLangLearnAccordion, EasyLangLearnAccordionItem
from EasyLangLearnInput import EasyLangLearnInputSwitch
from EasyLangLearnWidgets import ListBoxItemButton, MessageBox

import DragonLib.DateTools
from Business.Exam import Exam


class EasyLangLearnScreen(Screen):
	def load_data(self, parent):
		pass

	def next_page(self, item=None):
		self.parent.go_next(False)


class EasyLangLearnScreenHome(EasyLangLearnScreen):
	layout = None

	def on_enter(self, *args):
		super(EasyLangLearnScreenHome, self).on_enter(*args)

		if self.layout is None:
			self.layout = BoxLayout(orientation='vertical')
			self.add_widget(self.layout)

			Logger.info("PATH: " + os.getcwd())

			try:
				languages = ExamConfig.get_languages({'PATH': self.parent.path})
			except sqlite3.OperationalError as ex:
				self.layout.add_widget(
					Label(text="[color=ff0000]Грешка при зареждането на базата данни:\n%s[/color]" % ex.message,
					      markup=True, halign='center'))
			else:
				for language in languages:
					btn = EasyLangLearnButtonLang(language['SHIF'], language['ID'], language['NAME'])

					self.layout.add_widget(btn)

	def next_page(self, lang_id):
		info = False

		if self.parent.exam_options['LANGUAGE'] != lang_id:
			self.parent.init_options(LANGUAGE=lang_id)

			info = True

		self.parent.go_next(info)


class EasyLangLearnScreenClassifications(EasyLangLearnScreen):
	accordion = None

	def load_data(self, parent):
		classifications = ExamConfig.get_lang_classifications(
			{
				'PATH': parent.path,
				'ID': parent.exam_options['LANGUAGE']
			})

		if self.accordion is None:
			self.accordion = EasyLangLearnAccordion()

			self.add_widget(self.accordion)

		for classification in classifications:
			logs = ExamConfig.get_classification_log({'PATH': parent.path, 'ID': classification['ID']})

			item = EasyLangLearnAccordionItem(classification['ID'], classification['NAME'], logs)

			self.accordion.add_widget(item)

	def next_page(self, item):
		info = False

		if self.parent.exam_options['CLASSIFICATION'] != item.classification_id:
			self.parent.init_options(LANGUAGE=self.parent.exam_options['LANGUAGE'],
			                         CLASSIFICATION=item.classification_id)

			info = True

		self.parent.go_next(info)

	def load_from_file(self, item):
		pass


class EasyLangLearnScreenSetup(EasyLangLearnScreen):
	test_type = ObjectProperty()
	test_type_shif = StringProperty()
	from_date = ObjectProperty()
	to_date = ObjectProperty()
	words_count = ObjectProperty()
	guess_count = ObjectProperty()

	included_categories = ObjectProperty()
	excluded_categories = ObjectProperty()

	def load_data(self, parent):
		exam_types = ExamConfig.get_exam_types(
			{
				'PATH': parent.path
			})

		info = ExamConfig.get_classification_info(
			{
				'PATH': parent.path,
				'ID': parent.exam_options['CLASSIFICATION']
			})

		self.from_date.text = DragonLib.DateTools.format_sql_str_to_bgdate_str(info['MIN_DATE'])
		self.to_date.text = DragonLib.DateTools.format_sql_str_to_bgdate_str(info['MAX_DATE'])

		self.words_count.number = info['WORD_COUNT']

		self.guess_count.number = 2

		for exam_type in exam_types:
			button = ListBoxItemButton(item_id=exam_type['ID'], item_shif=exam_type['SHIF'], text=exam_type['NAME'])
			button.bind(on_press=self.selection_changed)

			self.test_type.list.add_widget(button)

		for category in info['CATEGORIES']:
			#включената категория
			category_in = EasyLangLearnInputSwitch(label=category['NAME'], state=True, id=category['ID'])

			self.included_categories.add_widget(category_in)

			#изключената категория
			category_ex = EasyLangLearnInputSwitch(label=category['NAME'], state=False, id=category['ID'])

			self.excluded_categories.add_widget(category_ex)

	def next_page(self):
		self.parent.exam_options['EXAM_TYPE'] = self.test_type_shif
		self.parent.exam_options['FROM_DATE'] = DragonLib.DateTools.format_bgdate_str_to_sql_str(self.from_date.text)
		self.parent.exam_options['TO_DATE'] = DragonLib.DateTools.format_bgdate_str_to_sql_str(self.to_date.text)
		self.parent.exam_options['WORD_COUNT'] = self.words_count.number
		self.parent.exam_options['TEST_WORD_NUM'] = self.guess_count.number

		self.parent.exam_options['CATEGORIES_INCLUDED'] = []
		for category in self.included_categories.children:
			if category.switch_input.active:
				self.parent.exam_options['CATEGORIES_INCLUDED'].append(str(category.id))

		self.parent.exam_options['CATEGORIES_EXCLUDED'] = []
		for category in self.excluded_categories.children:
			if category.switch_input.active:
				self.parent.exam_options['CATEGORIES_EXCLUDED'].append(str(category.id))

		self.parent.exam = Exam(self.parent.exam_options)

		if self.parent.exam.is_valid_test():
			self.parent.go_next(True)
		else:
			MessageBox("Невалидни данни за тест", title="Грешка").open()

	def selection_changed(self, item):
		self.test_type.button.text = item.text
		self.test_type_shif = item.item_shif


class EasyLangLearnScreenExam(EasyLangLearnScreen):
	word = None

	word_label = ObjectProperty()
	word_answer = ObjectProperty()
	word_info = ObjectProperty()

	def load_data(self, parent):
		new_word = parent.exam.get_new_word()

		self.word = new_word['WORD']
		if self.word != '':
			self.word_label.text = self.word

			self.word_answer.bind(on_text_validate=self.on_enter)
		else:
			self.finish_exam(new_word['RESULT'])

	def on_enter(self, instance=None):
		#self.check_word()
		Clock.schedule_once(self.check_word)

	def check_word(self, event=None):
		if self.word_answer.text:
			check = self.parent.exam.check_word(answer=self.word_answer.text.decode('utf-8', 'ignore'))

			info = ''

			if check['CORRECT']:
				info = u"[b][color=00FF00]Верен отговор![/color][/b]\n\n"
			else:
				info = u"[b][color=FF0000]Грешен отговор![/color][/b]\n\n"

			info += u"[color=FFFF00]%s[/color]\n\nсе превежда\n\n[color=FFA500]%s[/color]" % (self.word, check['TRANSLATION'])

			self.word_info.text = info

			new_word = self.parent.exam.get_new_word()

			self.word = new_word['WORD']
			if self.word != '':
				self.word_label.text = self.word

				self.word_answer.text = ''
			else:
				self.finish_exam(new_word['RESULT'])

		self.word_answer.focus = True

	def finish_exam(self, info=None):
		display_info = u"Край на теста"
		#info = self.parent.exam.get_exam_info()

		if info:
			display_info = u"""[b]Брой думи: %d[/b]
[b]Процент познати думи: %.2f[/b]
""" % (info['WORD_COUNT'], info['EXAM_PERCENT'])

		MessageBox(display_info, title="Резултат от теста", callback=self.parent.go_prev).open()


